/**
 * 地址解析工具
 * @description 基于腾讯地图API的地址解析功能
 */

import { buildApiUrl, isApiKeyConfigured, TENCENT_MAP_CONFIG } from './mapConfig'

/**
 * 地址解析结果接口
 */
export interface GeocodeResult {
  latitude: number
  longitude: number
  address: string
  name: string
  province?: string
  city?: string
  district?: string
  street?: string
  streetNumber?: string
}

/**
 * 地址解析（地址转坐标）
 * @param address 要解析的地址
 * @returns Promise<GeocodeResult>
 */
export const geocodeAddress = async (address: string): Promise<GeocodeResult> => {
  try {
    // 检查API密钥是否已配置
    if (!isApiKeyConfigured()) {
      throw new Error('腾讯地图API密钥未配置')
    }
    
    // 构建代理请求URL
    const url = new URL(TENCENT_MAP_CONFIG.GEOCODER_URL, window.location.origin)
    url.searchParams.append('address', address)
    url.searchParams.append('key', TENCENT_MAP_CONFIG.API_KEY)
    url.searchParams.append('output', 'json')
    
    console.log('请求腾讯地图API（通过代理）:', url.toString())
    
    // 发起请求
    const response = await fetch(url.toString())
    
    if (!response.ok) {
      throw new Error(`请求失败: ${response.status} ${response.statusText}`)
    }
    
    const data = await response.json()
    
    if (data.status === 0) {
      const result = data.result
      const location = result.location
      const addressComponents = result.address_components || {}
      
      // 构建结构化地址
      const structuredAddress = [
        addressComponents.province,
        addressComponents.city,
        addressComponents.district,
        addressComponents.street,
        addressComponents.street_number
      ].filter(Boolean).join('')
      
      return {
        latitude: location.lat,
        longitude: location.lng,
        address: structuredAddress || result.title,
        name: `${addressComponents.city}${addressComponents.district}`,
        province: addressComponents.province,
        city: addressComponents.city,
        district: addressComponents.district,
        street: addressComponents.street,
        streetNumber: addressComponents.street_number
      }
    } else {
      throw new Error(`地址解析失败: ${data.message}`)
    }
  } catch (error) {
    console.error('地址解析错误:', error)
    // 解析失败时返回默认值
    return {
      latitude: TENCENT_MAP_CONFIG.DEFAULT_LOCATION.latitude,
      longitude: TENCENT_MAP_CONFIG.DEFAULT_LOCATION.longitude,
      address: '地址解析失败，请手动选择',
      name: '未知地点'
    }
  }
}

/**
 * 批量地址解析
 * @param addresses 地址数组
 * @returns Promise<GeocodeResult[]>
 */
export const batchGeocodeAddresses = async (addresses: string[]): Promise<GeocodeResult[]> => {
  const results: GeocodeResult[] = []
  
  for (const address of addresses) {
    try {
      const result = await geocodeAddress(address)
      results.push(result)
    } catch (error) {
      console.error(`地址解析失败: ${address}`, error)
      results.push({
        latitude: TENCENT_MAP_CONFIG.DEFAULT_LOCATION.latitude,
        longitude: TENCENT_MAP_CONFIG.DEFAULT_LOCATION.longitude,
        address: '解析失败',
        name: '未知地点'
      })
    }
  }
  
  return results
}

/**
 * 逆地址解析（坐标转地址）
 * @param latitude 纬度
 * @param longitude 经度
 * @returns Promise<GeocodeResult>
 */
export const reverseGeocode = async (latitude: number, longitude: number): Promise<GeocodeResult> => {
  try {
    // 检查API密钥是否已配置
    if (!isApiKeyConfigured()) {
      throw new Error('腾讯地图API密钥未配置')
    }
    
    // 构建代理请求URL
    const url = new URL(TENCENT_MAP_CONFIG.REVERSE_GEOCODER_URL, window.location.origin)
    url.searchParams.append('location', `${latitude},${longitude}`)
    url.searchParams.append('key', TENCENT_MAP_CONFIG.API_KEY)
    url.searchParams.append('output', 'json')
    
    console.log('请求腾讯地图API（通过代理）:', url.toString())
    
    // 发起请求
    const response = await fetch(url.toString())
    
    if (!response.ok) {
      throw new Error(`请求失败: ${response.status} ${response.statusText}`)
    }
    
    const data = await response.json()
    
    if (data.status === 0) {
      const result = data.result
      const addressComponents = result.address_components
      
      // 构建结构化地址
      const structuredAddress = [
        addressComponents.province,
        addressComponents.city,
        addressComponents.district,
        addressComponents.street,
        addressComponents.street_number
      ].filter(Boolean).join('')
      
      return {
        latitude: latitude,
        longitude: longitude,
        address: structuredAddress || result.title,
        name: `${addressComponents.city}${addressComponents.district}`,
        province: addressComponents.province,
        city: addressComponents.city,
        district: addressComponents.district,
        street: addressComponents.street,
        streetNumber: addressComponents.street_number
      }
    } else {
      throw new Error(`逆地址解析失败: ${data.message}`)
    }
  } catch (error) {
    console.error('逆地址解析错误:', error)
    return {
      latitude: latitude,
      longitude: longitude,
      address: '逆地址解析失败',
      name: '未知地点'
    }
  }
}

/**
 * 验证地址格式
 * @param address 地址字符串
 * @returns boolean
 */
export const validateAddress = (address: string): boolean => {
  if (!address || typeof address !== 'string') {
    return false
  }
  
  // 基本格式验证
  const trimmedAddress = address.trim()
  if (trimmedAddress.length < 5) {
    return false
  }
  
  // 检查是否包含省市区信息
  const hasProvince = /省|市|自治区|特别行政区/.test(trimmedAddress)
  const hasCity = /市|区|县/.test(trimmedAddress)
  
  return hasProvince || hasCity
}

/**
 * 格式化地址
 * @param address 原始地址
 * @returns 格式化后的地址
 */
export const formatAddress = (address: string): string => {
  if (!address) return ''
  
  // 移除多余空格
  let formatted = address.replace(/\s+/g, ' ').trim()
  
  // 统一标点符号
  formatted = formatted.replace(/，/g, ',')
  formatted = formatted.replace(/。/g, '.')
  
  return formatted
} 